package com.netposa.datawarehouse.bodysearch.service.impl;

import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netposa.appwebres.exception.WebResException;
import com.netposa.appwebres.extend.Checks;
import com.netposa.appwebres.extend.Page;
import com.netposa.datawarehouse.bodysearch.cache.CacheHelper;
import com.netposa.datawarehouse.bodysearch.config.BodyQueryProps;
import com.netposa.datawarehouse.bodysearch.consumer.SearchServiceFeign;
import com.netposa.datawarehouse.bodysearch.mappers.BodyFeatureMapper;
import com.netposa.datawarehouse.bodysearch.mappers.BodyOriginalMapper;
import com.netposa.datawarehouse.bodysearch.service.BodyService;
import com.netposa.datawarehouse.bodysearch.service.RequestIdService;
import com.netposa.datawarehouse.bodysearch.utils.BitOp;
import com.netposa.datawarehouse.bodysearch.web.model.Body;
import com.netposa.datawarehouse.bodysearch.web.model.BodyCondition;
import com.netposa.datawarehouse.bodysearch.web.model.BodyDownloadCondition;
import com.netposa.datawarehouse.bodysearch.web.model.Querypolicy;
import com.netposa.datawarehouse.bodysearch.web.model.RecordIdsCondition;
import com.netposa.datawarehouse.bodysearch.web.vo.BodyOriginalVO;
import com.netposa.datawarehouse.bodysearch.web.vo.BodyVO;
import com.netposa.datawarehouse.component.entity.BodyFeature;
import com.netposa.datawarehouse.component.entity.BodyOriginal;
import com.netposa.datawarehouse.ftr.DataSearchClient;
import com.netposa.datawarehouse.ftr.core.SearchDataEntry;
import com.netposa.datawarehouse.ftr.core.SearchDataRequest;
import com.netposa.datawarehouse.ftr.core.SearchDataResponse;
import com.netposa.datawarehouse.ftr.core.SearchParamEntry;
import com.netposa.datawarehouse.ftr.schema.IndexTypes;
import com.netposa.library.api.IDevicesCache;
import com.netposa.library.api.IDictionaryCache;
import com.netposa.library.datawarehouse.aggregate.utils.AggregatorUtils;
import com.netposa.library.datawarehouse.aggregate.utils.AggregatorUtils.SearchingColors;
import com.netposa.library.model.DeviceObj;
import com.netposa.npwonder.base.model.ResponseData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class BodyServiceImpl implements BodyService {
   private static final Logger log = LoggerFactory.getLogger(BodyServiceImpl.class);
   @Autowired
   private BodyOriginalMapper bodyOriginalMapper;
   @Autowired
   private BodyFeatureMapper bodyFeatureMapper;
   @Autowired
   private IDevicesCache devicesCache;
   @Autowired
   private DataSearchClient dataSearchClient;
   @Autowired
   private RequestIdService requestIdService;
   @Autowired
   private SearchServiceFeign searchServiceFeign;
   @Autowired
   private CacheHelper cacheHelper;
   @Value("${netposa.aggregator.es.switch}")
   private boolean needEs;
   private Integer DEFAULT_MARGINAL_COUNT = 100000;
   @Value("${mybatis.mapper-locations}")
   private String mybatisMapperLocations;
   @Autowired
   private BodyQueryProps props;
   @Autowired
   private IDictionaryCache dictionaryCache;
   private Cache deviceObjCache;

   public BodyServiceImpl() {
      this.deviceObjCache = CacheBuilder.newBuilder().expireAfterAccess(5L, TimeUnit.MINUTES).maximumSize(1000L).weakValues().build();
   }

   public BodyVO getBodyByRecordId(String recordId) {
      BodyFeature bodyFeature = this.bodyFeatureMapper.queryBodyFeatureByRecordId(recordId);
      BodyOriginal bodyOriginal = this.bodyOriginalMapper.queryBodyOriginalByRecordId(recordId);
      return this.wrapBodyVO(this.wrapBody(bodyOriginal, bodyFeature));
   }

   public BodyOriginalVO getBodyOriginById(String recordId) {
      BodyOriginal bodyOriginal = this.bodyOriginalMapper.queryBodyOriginalByRecordId(recordId);
      return this.wrapBodyOriginalVO(bodyOriginal);
   }

   public List getBodyOriginalByIds(RecordIdsCondition condition) {
      List recordList = Splitter.on(",").splitToList(condition.getRecordIds());
      if (recordList.isEmpty()) {
         return Lists.newArrayList();
      } else {
         List bodyOriginalList = this.fetchBodyOriginalByIds(recordList);
         return this.wrapBodyOriginalVOList(bodyOriginalList);
      }
   }

   public void deleteBody(String ids) {
      if (StringUtils.isNotBlank(ids)) {
         List idList = Arrays.asList(ids.split(","));
         this.bodyOriginalMapper.deleteOriginalByRecordId(idList);
         this.bodyFeatureMapper.deleteFeatureByRecordId(idList);
      }

   }

   public BodyFeature getBodyFeatureById(String recordId) {
      BodyFeature bodyFeature = this.bodyFeatureMapper.queryBodyFeatureByRecordId(recordId);
      return bodyFeature;
   }

   public List topX(Integer count, String deviceId, Long startTime, Long endTime) {
      List<BodyVO>  bodyVOList = new ArrayList();
      Checks.checkRange(count, 1, Integer.MAX_VALUE);
      Map deviceObjMap = new HashMap();
      List bodyList = null;
      if (StringUtils.isNotBlank(deviceId) && this.getCameraInfo(deviceId) != null) {
         deviceObjMap.put(deviceId, this.getCameraInfo(deviceId));
      }

      if (endTime == null) {
         endTime = System.currentTimeMillis();
      }

      if (startTime == null) {
         startTime = endTime - 86400000L;
      }

      List bodyOriginalList = this.bodyOriginalMapper.queryTopByDeviceId(deviceId, count, startTime, endTime);
      if (bodyOriginalList.isEmpty()) {
         return bodyVOList;
      } else {
         List recordIdList = new ArrayList();
         Iterator var10 = bodyOriginalList.iterator();

         while(var10.hasNext()) {
            BodyOriginal bodyOriginal = (BodyOriginal)var10.next();
            recordIdList.add(bodyOriginal.getRecordId());
         }

         List bodyFeatureList = this.bodyFeatureMapper.queryByRecordIds(recordIdList);
         bodyList = this.wrapBodyList(bodyOriginalList, bodyFeatureList);
         if (!deviceObjMap.isEmpty()) {
            bodyVOList = this.WrapBodyVOListByDeviceMap(deviceObjMap, bodyList);
         } else {
            bodyVOList = this.wrapBodyVOList(bodyList);
         }

         return bodyVOList;
      }
   }

   public List downloadExport(BodyDownloadCondition condition) {
      List bodyVOList;
      if (condition.getDownloadSize() != null && condition.getDownloadSize() > 0) {
         bodyVOList = this.getBodyByParams(condition);
      } else {
         bodyVOList = this.getBodyByIds(condition.getRecordIds());
      }

      return bodyVOList;
   }

   public Page getBodyOriginByParams(BodyCondition condition) {
      this.processParm(condition);
      String searchContent = condition.getSearchText();
      if (StringUtils.isNotBlank(condition.getSearchText())) {
         if (this.needEs) {
            return this.fullTextSearch(condition);
         }

         List words = AggregatorUtils.str2List(searchContent);
         if (CollectionUtils.isEmpty(words)) {
            return new Page();
         }

         List flags = new ArrayList(2);
         List dictionaries = this.dictionaryCache.get(SearchingColors.COAT_COLORS.getValue());
         Integer value = AggregatorUtils.convert2ColorCode(dictionaries, words);
         if (!value.equals(0)) {
            flags.add(true);
            condition.setUpperColor("" + value);
         }

         dictionaries = this.dictionaryCache.get(SearchingColors.UNDER_CLOTHES_COLORS.getValue());
         value = AggregatorUtils.convert2ColorCode(dictionaries, words);
         if (!value.equals(0)) {
            flags.add(true);
            condition.setLowerColor("" + value);
         }

         if (CollectionUtils.isEmpty(flags) || !flags.contains(true)) {
            return new Page();
         }
      }

      return this.getBodyList(condition);
   }

   private Page getBodyList(BodyCondition condition) {
      if (!StringUtils.isEmpty(condition.getDeviceId())) {
         condition.setDeviceId("('" + condition.getDeviceId().replace(",", "','") + "')");
      }

      Integer total = 0;
      if (StringUtils.isNotBlank(condition.getRequestId())) {
         RequestIdService.RequestAssociateValue associateValue = this.requestIdService.get(condition.getRequestId());
         if (associateValue == null) {
            total = this.explainComputeCount(condition);
         } else {
            condition.setLastAbsTime(associateValue.getLastTime());
            condition.setLastRecordId(associateValue.getLastRecordId());
            total = associateValue.getCount();
         }
      } else {
         total = this.explainComputeCount(condition);
      }

      condition.setQueryFeature(this.hasAttributeParam(condition));
      this.assemblyQueryTime(condition);
      this.initQueryListPolicy(condition);
      long startQueryList = System.currentTimeMillis();
      List bodyList = this.queryList(condition);
      long endQueryList = System.currentTimeMillis();
      log.debug("query by condition cost time ------>{}ms", endQueryList - startQueryList);
      if (bodyList != null && bodyList.size() >= 1) {
         long startQueryDetail = System.currentTimeMillis();
         List originalList = this.convertBodyOriginalVO(bodyList, condition);
         long endQueryDetail = System.currentTimeMillis();
         log.debug("query by ids cost time ------>{}ms", endQueryDetail - startQueryDetail);
         if (originalList != null && originalList.size() > 0) {
            RequestIdService.RequestAssociateValue associateValue = new RequestIdService.RequestAssociateValue();
            associateValue.setCount(total);
            BodyOriginalVO bodyOriginalVO = (BodyOriginalVO)originalList.get(originalList.size() - 1);
            associateValue.setLastRecordId(bodyOriginalVO.getRecordId());
            associateValue.setLastTime(bodyOriginalVO.getAbsTime());
            this.setAssociateValue(condition, associateValue);
         }

         condition.updatePageInfo(originalList, total);
         condition.setQuerypolicy((Querypolicy)null);
         return condition;
      } else {
         condition.setQuerypolicy((Querypolicy)null);
         return condition;
      }
   }

   private List<BodyOriginalVO> convertBodyOriginalVO(List<Body> bodyList, BodyCondition condition) {
      List<BodyOriginal> bodyOriginalList = Lists.newArrayList();
      if (condition.isQueryFeature()) {
         bodyOriginalList = this.fetchBodyOriginalForFeature(bodyList);
      } else {
         bodyOriginalList = this.fetchBodyOriginalForYouhua(bodyList, condition);
      }

      if (bodyOriginalList.isEmpty()) {
         return Lists.newArrayList();
      } else {
         List<BodyOriginalVO> originalVoList = Lists.transform(bodyOriginalList.stream().filter((o) -> {
            return !Objects.isNull(o);
         }).collect(Collectors.toList()), new Function<BodyOriginal,BodyOriginalVO>() {
            @Nullable
            public BodyOriginalVO apply(@Nullable BodyOriginal bodyOriginal) {
               BodyOriginalVO bodyOriginalVO = new BodyOriginalVO();
               BeanUtils.copyProperties(bodyOriginal, bodyOriginalVO);
               if (StringUtils.isNotBlank(bodyOriginalVO.getDeviceId())) {
                  DeviceObj deviceObj = BodyServiceImpl.this.devicesCache.get(bodyOriginalVO.getDeviceId());
                  if (deviceObj != null) {
                     bodyOriginalVO.setDeviceName(deviceObj.getName());
                     bodyOriginalVO.setLongitude(deviceObj.getLongitude());
                     bodyOriginalVO.setLatitude(deviceObj.getLatitude());
                  }
               }

               return bodyOriginalVO;
            }
         }).stream().sorted((o1, o2) -> {
            return (int)(o2.getAbsTime() - o1.getAbsTime());
         }).collect(Collectors.toList());
         return originalVoList;
      }
   }

   private void assemblyQueryTime(BodyCondition condition) {
      if (condition.getLastAbsTime() != null) {
         if ("ASC".equalsIgnoreCase(condition.getOrder())) {
            condition.setStartTime(condition.getLastAbsTime());
         }

         if ("DESC".equalsIgnoreCase(condition.getOrder())) {
            condition.setEndTime(condition.getLastAbsTime());
         }
      }

   }

   private void initQueryListPolicy(BodyCondition condition) {
      Querypolicy policy = Querypolicy.builder().defaultQueryTimeRange((long)this.props.getInitRangeMs()).step(1).order(condition.getOrder()).srcStart(condition.getStartTime()).srcEnd(condition.getEndTime()).lastPassId(condition.getLastRecordId()).result(new ArrayList()).pageLimit(condition.getPageSize()).build().first();
      condition.setQuerypolicy(policy);
   }

   private List queryList(BodyCondition condition) {
      while(!this.isFinish(condition)) {
         long query_start = System.currentTimeMillis();
         condition.getQuerypolicy().addResult(this.doQuery(condition)).next();
         long query_end = System.currentTimeMillis();
         log.debug("本次查询耗时:--->" + (query_end - query_start) + "ms");
      }

      return condition.getQuerypolicy().getResult();
   }

   private List doQuery(BodyCondition condition) {
      List result = null;
      if (condition.isQueryFeature()) {
         result = this.bodyFeatureMapper.getFeatureList(condition);
      } else {
         result = this.bodyOriginalMapper.getOriginalListYouhua(condition);
      }

      return (List)(result == null ? Lists.newArrayList() : result);
   }

   private boolean isFinish(BodyCondition condition) {
      Querypolicy querypolicy = condition.getQuerypolicy();
      if (querypolicy.getPageLimit() <= 0) {
         return true;
      } else {
         return querypolicy.getStartTime() == querypolicy.getEndTime() && querypolicy.queryOnce();
      }
   }

   private void processParm(BodyCondition condition) {
      String ageSegmentStr;
      ArrayList headMarkerList;
      int i;
      if (StringUtils.isNotEmpty(condition.getHeadMarkerStr())) {
         ageSegmentStr = condition.getHeadMarkerStr();
         headMarkerList = new ArrayList();
         String[] var4 = ageSegmentStr.split(",");
         i = var4.length;

         for(int var6 = 0; var6 < i; ++var6) {
            String headMarker = var4[var6];
            headMarkerList.add(this.generateValue(headMarker));
         }

         Integer[] headMarkerArray = new Integer[headMarkerList.size()];
         List headMarkerStrList = BitOp.getUnion((Integer[])headMarkerList.toArray(headMarkerArray));
         condition.setHeadMarkerList(headMarkerStrList);
      }

      if (StringUtils.isNotEmpty(condition.getBagTypeStr())) {
         ageSegmentStr = condition.getBagTypeStr();
         headMarkerList = null;
         List bodyAppendageList = new ArrayList();
         List bodyAppendageStrList = new ArrayList();
         if ("-1".equals(ageSegmentStr)) {
            Integer bodyAppendage1 = -1;
            Integer bodyAppendage2 = 0;
            ((List)bodyAppendageStrList).add(bodyAppendage1);
            ((List)bodyAppendageStrList).add(bodyAppendage2);
         } else {
            Integer bodyAppendage = this.generateValue(ageSegmentStr.split(","));
            String[] var17 = ageSegmentStr.split(",");
            int var20 = var17.length;

            for(int var8 = 0; var8 < var20; ++var8) {
               String bagType = var17[var8];
               bodyAppendageList.add(this.generateValue(bagType));
            }

            Integer[] bodyAppendageArray = new Integer[bodyAppendageList.size()];
            bodyAppendageStrList = BitOp.getUnion((Integer[])bodyAppendageList.toArray(bodyAppendageArray));
         }

         condition.setBodyAppendageList((List)bodyAppendageStrList);
      }

      if (StringUtils.isNotEmpty(condition.getAgeSegmentStr())) {
         ageSegmentStr = condition.getAgeSegmentStr();
         String[] ageStr = ageSegmentStr.split(",");
         int[] ageSegment = new int[ageStr.length];

         for(i = 0; i < ageStr.length; ++i) {
            ageSegment[i] = Integer.parseInt(ageStr[i]);
         }

         condition.setAgeSegmentList(ageSegment);
      }

      if (condition.getPageSize() == null || condition.getPageSize() < 1) {
         throw new WebResException("400");
      }
   }

   private Body wrapBody(BodyOriginal bodyOriginal, BodyFeature bodyFeature) {
      if (bodyFeature == null && bodyOriginal == null) {
         return null;
      } else {
         Body body = new Body();
         if (bodyFeature != null) {
            BeanUtils.copyProperties(bodyFeature, body);
         }

         if (bodyOriginal != null) {
            BeanUtils.copyProperties(bodyOriginal, body, new String[]{"location"});
         }

         return body;
      }
   }

   private BodyVO wrapBodyVO(Body body) {
      if (body != null) {
         BodyVO bodyVO = new BodyVO();
         BeanUtils.copyProperties(body, bodyVO);
         if (StringUtils.isNotBlank(body.getDeviceId())) {
            DeviceObj deviceObj = new DeviceObj();

            try {
               deviceObj = this.devicesCache.get(body.getDeviceId());
            } catch (Exception var5) {
               log.error("从redis中获取设备详情失败:", var5);
            }

            if (deviceObj != null) {
               bodyVO.setDeviceName(deviceObj.getName());
               bodyVO.setNodeType(deviceObj.getType());
               bodyVO.setLatitude(deviceObj.getLatitude());
               bodyVO.setLongitude(deviceObj.getLongitude());
               bodyVO.setCameraType(deviceObj.getCameraType());
            }
         }

         String str;
         if (null != body.getHeadMarker()) {
            if (body.getHeadMarker() != -1 && body.getHeadMarker() != 0) {
               str = this.generateCode(body.getHeadMarker());
               bodyVO.setHeadMarkerStr(str);
            } else {
               bodyVO.setHeadMarkerStr(body.getHat().toString());
            }
         }

         if (null != body.getBodyAppendage()) {
            if (body.getBodyAppendage() != -1 && body.getBodyAppendage() != 0) {
               str = this.generateCode(body.getBodyAppendage());
               bodyVO.setBodyAppendageStr(str);
            } else {
               bodyVO.setBodyAppendageStr(body.getBagType().toString());
            }
         }

         return bodyVO;
      } else {
         return null;
      }
   }

   private BodyOriginalVO wrapBodyOriginalVO(BodyOriginal bodyOriginal) {
      BodyOriginalVO bodyOriginalVO = new BodyOriginalVO();
      BeanUtils.copyProperties(bodyOriginal, bodyOriginalVO);
      DeviceObj cameraInfo = this.getCameraInfo(bodyOriginal.getDeviceId());
      if (cameraInfo != null) {
         bodyOriginalVO.setDeviceName(cameraInfo.getName());
         if (cameraInfo.getLatitude() != null) {
            bodyOriginalVO.setLatitude(cameraInfo.getLatitude());
         }

         if (cameraInfo.getLatitude() != null) {
            bodyOriginalVO.setLongitude(cameraInfo.getLongitude());
         }
      }

      return bodyOriginalVO;
   }

   private List wrapBodyList(List bodyOriginalList, List bodyFeatureList) {
      List bodyList = new ArrayList(bodyOriginalList.size());
      Map bodyFeatureMap = new HashMap(bodyFeatureList.size());
      Iterator var5 = bodyFeatureList.iterator();

      while(var5.hasNext()) {
         BodyFeature bodyFeature = (BodyFeature)var5.next();
         bodyFeatureMap.put(bodyFeature.getRecordId(), bodyFeature);
      }

      var5 = bodyOriginalList.iterator();

      while(var5.hasNext()) {
         BodyOriginal bodyOriginal = (BodyOriginal)var5.next();
         BodyFeature bodyFeature = (BodyFeature)bodyFeatureMap.get(bodyOriginal.getRecordId());
         Body body = this.wrapBody(bodyOriginal, bodyFeature);
         bodyList.add(body);
      }

      return bodyList;
   }

   private List wrapBodyVOList(List bodyList) {
      List bodyVOList = new ArrayList();
      Map deviceObjMap = new HashMap();

      BodyVO bodyVO;
      for(Iterator var4 = bodyList.iterator(); var4.hasNext(); bodyVOList.add(bodyVO)) {
         Body body = (Body)var4.next();
         bodyVO = new BodyVO();
         BeanUtils.copyProperties(body, bodyVO);
         if (StringUtils.isNotBlank(bodyVO.getDeviceId())) {
            DeviceObj camera = null;
            if (deviceObjMap.containsKey(bodyVO.getDeviceId())) {
               camera = (DeviceObj)deviceObjMap.get(bodyVO.getDeviceId());
            } else {
               camera = this.getCameraInfo(bodyVO.getDeviceId());
               if (camera != null) {
                  deviceObjMap.put(bodyVO.getDeviceId(), camera);
               }
            }

            if (camera != null) {
               bodyVO.setDeviceName(camera.getName());
               new DeviceObj();
               DeviceObj deviceObj = this.devicesCache.get(bodyVO.getDeviceId());
               bodyVO.setNodeType(deviceObj.getType());
               if (camera.getLatitude() != null) {
                  bodyVO.setLatitude(camera.getLatitude());
               }

               if (camera.getLatitude() != null) {
                  bodyVO.setLongitude(camera.getLongitude());
               }
            }
         }
      }

      return bodyVOList;
   }

   private List wrapBodyOriginalVOList(List bodyOriginalList) {
      List bodyOriginalVOList = new ArrayList(bodyOriginalList.size());
      Map deviceObjMap = new HashMap();

      BodyOriginalVO bodyOriginalVO;
      for(Iterator var4 = bodyOriginalList.iterator(); var4.hasNext(); bodyOriginalVOList.add(bodyOriginalVO)) {
         BodyOriginal bodyOriginal = (BodyOriginal)var4.next();
         bodyOriginalVO = new BodyOriginalVO();
         BeanUtils.copyProperties(bodyOriginal, bodyOriginalVO);
         if (StringUtils.isNotBlank(bodyOriginalVO.getDeviceId())) {
            DeviceObj camera = null;
            if (deviceObjMap.containsKey(bodyOriginalVO.getDeviceId())) {
               camera = (DeviceObj)deviceObjMap.get(bodyOriginalVO.getDeviceId());
            } else {
               camera = this.getCameraInfo(bodyOriginalVO.getDeviceId());
               if (camera != null) {
                  deviceObjMap.put(bodyOriginalVO.getDeviceId(), camera);
               }
            }

            if (camera != null) {
               bodyOriginalVO.setDeviceName(camera.getName());
               if (camera.getLatitude() != null) {
                  bodyOriginalVO.setLatitude(camera.getLatitude());
               }

               if (camera.getLatitude() != null) {
                  bodyOriginalVO.setLongitude(camera.getLongitude());
               }
            }
         }
      }

      return bodyOriginalVOList;
   }

   private List WrapBodyVOListByDeviceMap(Map deviceObjMap, List bodyList) {
      List bodyVOList = new ArrayList(bodyList.size());

      BodyVO bodyVO;
      for(Iterator var4 = bodyList.iterator(); var4.hasNext(); bodyVOList.add(bodyVO)) {
         Body body = (Body)var4.next();
         bodyVO = new BodyVO();
         BeanUtils.copyProperties(body, bodyVO);
         DeviceObj cameraInfo = (DeviceObj)deviceObjMap.get(bodyVO.getDeviceId());
         if (cameraInfo != null) {
            bodyVO.setDeviceName(cameraInfo.getName());
            if (cameraInfo.getLatitude() != null) {
               bodyVO.setLatitude(cameraInfo.getLatitude());
            }

            if (cameraInfo.getLatitude() != null) {
               bodyVO.setLongitude(cameraInfo.getLongitude());
            }
         }
      }

      return bodyVOList;
   }

   private List WrapBodyOriginalVOListByDeviceMap(Map deviceObjMap, List bodyOriginalList) {
      List bodyOriginalVOList = new ArrayList(bodyOriginalList.size());

      BodyOriginalVO bodyVO;
      for(Iterator var4 = bodyOriginalList.iterator(); var4.hasNext(); bodyOriginalVOList.add(bodyVO)) {
         BodyOriginal bodyOriginal = (BodyOriginal)var4.next();
         bodyVO = new BodyOriginalVO();
         BeanUtils.copyProperties(bodyOriginal, bodyVO);
         DeviceObj cameraInfo = (DeviceObj)deviceObjMap.get(bodyVO.getDeviceId());
         if (cameraInfo != null) {
            bodyVO.setDeviceName(cameraInfo.getName());
            if (cameraInfo.getLatitude() != null) {
               bodyVO.setLatitude(cameraInfo.getLatitude());
            }

            if (cameraInfo.getLatitude() != null) {
               bodyVO.setLongitude(cameraInfo.getLongitude());
            }
         }
      }

      return bodyOriginalVOList;
   }

   private Page accurateRetrieval(BodyCondition condition) {
      Integer total = 0;
      Map deviceObjMap = new HashMap();
      if (!StringUtils.isEmpty(condition.getDeviceId())) {
         List deviceIdList = Arrays.asList(condition.getDeviceId().split(","));
         Iterator var5 = deviceIdList.iterator();

         while(var5.hasNext()) {
            String deviceId = (String)var5.next();
            DeviceObj obj = this.getCameraInfo(deviceId);
            if (obj != null) {
               deviceObjMap.put(deviceId, obj);
            }
         }

         condition.setDeviceId("('" + condition.getDeviceId().replace(",", "','") + "')");
      }

      if (StringUtils.isNotBlank(condition.getRequestId())) {
         RequestIdService.RequestAssociateValue associateValue = this.requestIdService.get(condition.getRequestId());
         if (associateValue == null) {
            condition.setOffset((condition.getCurrentPage() - 1) * condition.getPageSize());
            total = this.explainComputeCount(condition);
         } else {
            condition.setLastAbsTime(associateValue.getLastTime());
            condition.setLastRecordId(associateValue.getLastRecordId());
            total = associateValue.getCount();
         }

         return this.search(condition, total, deviceObjMap);
      } else {
         condition.setOffset((condition.getCurrentPage() - 1) * condition.getPageSize());
         total = this.explainComputeCount(condition);
         return this.search(condition, total, deviceObjMap);
      }
   }

   private BodyCondition search(BodyCondition condition, Integer total, Map deviceObjMap) {
      List<BodyOriginalVO> bodyOriginalVOList = new ArrayList<>();
      List<BodyOriginal> bodyOriginalList = new ArrayList<>();
      if (this.hasAttributeParam(condition)) {
         List bodyFeatureList = new ArrayList();
         if (condition.getLastAbsTime() != null) {
             bodyFeatureList = this.bodyFeatureMapper.queryFeatureByAccurateTime(condition);
            if (bodyFeatureList.size() < condition.getPageSize()) {
               this.queryOnFeatureCondition(bodyFeatureList, condition);
            }
         } else {
            this.queryOnFeatureCondition(bodyFeatureList, condition);
         }
      } else if (condition.getLastAbsTime() != null) {
         bodyOriginalList = this.bodyOriginalMapper.queryOriginalByAccurateTime(condition);
         if (bodyOriginalList.size() < condition.getPageSize()) {
            bodyOriginalList.addAll(this.bodyOriginalMapper.queryByCondition(condition));
         }
      }

      bodyOriginalList = this.bodyOriginalMapper.queryByCondition(condition);
      this.sort(bodyOriginalList, this.orderConvert(condition.getOrder()));
      if (StringUtils.isNotBlank(condition.getDeviceId())) {
         bodyOriginalVOList = this.WrapBodyOriginalVOListByDeviceMap(deviceObjMap, bodyOriginalList);
      } else {
         bodyOriginalVOList = this.wrapBodyOriginalVOList(bodyOriginalList);
      }

      if (!bodyOriginalList.isEmpty()) {
         RequestIdService.RequestAssociateValue associateValue = new RequestIdService.RequestAssociateValue();
         associateValue.setCount(total);
         BodyOriginal bodyOriginal = (BodyOriginal)bodyOriginalList.get(bodyOriginalList.size() - 1);
         associateValue.setLastRecordId(bodyOriginal.getRecordId());
         associateValue.setLastTime(bodyOriginal.getAbsTime());
         this.setAssociateValue(condition, associateValue);
      }

      condition.updatePageInfo(bodyOriginalVOList, total);
      return condition;
   }

   private List queryOnFeatureCondition(List bodyFeatures, BodyCondition condition) {
      List bodyOriginalList = new ArrayList();
      List bodyFeatureList = new ArrayList();
      bodyFeatureList.addAll(bodyFeatures);
      bodyFeatureList.addAll(this.bodyFeatureMapper.queryByCondition(condition));
      if (!bodyFeatureList.isEmpty()) {
         List recordIdList = new ArrayList();
         Iterator var6 = bodyFeatureList.iterator();

         while(var6.hasNext()) {
            BodyFeature bodyFeature = (BodyFeature)var6.next();
            recordIdList.add(bodyFeature.getRecordId());
         }

         bodyOriginalList = this.bodyOriginalMapper.queryByRecordIds(recordIdList);
      }

      return (List)bodyOriginalList;
   }

   public Integer explainComputeCount(BodyCondition condition) {
      Boolean flag = this.hasAttributeParam(condition);
      List explain;
      if (flag) {
         explain = this.bodyFeatureMapper.explainCount(condition);
      } else {
         explain = this.bodyOriginalMapper.explainCount(condition);
      }

      Integer count = 0;
      if (explain.isEmpty()) {
         throw new RuntimeException("Opaq explain exception.");
      } else {
         count = this.dealExplainResultForOpaq(explain);
         if (this.mybatisMapperLocations.contains("huaweicloud")) {
            count = this.dealExplainResultForHuaweiCloud(explain);
         }

         if (count <= this.DEFAULT_MARGINAL_COUNT && count > 0) {
            if (flag) {
               count = this.bodyFeatureMapper.accurateCount(condition);
            } else {
               count = this.bodyOriginalMapper.queryCountByCondition(condition);
            }
         }

         return count;
      }
   }

   private Integer dealExplainResultForOpaq(List result) {
      Integer count = 0;
      Iterator var3 = result.iterator();

      while(var3.hasNext()) {
         HashMap map = (HashMap)var3.next();
         Object rowObj = map.get("rows");
         if (rowObj != null) {
            if (rowObj instanceof Long) {
               count = count + ((Long)rowObj).intValue();
            } else {
               count = count + (Integer)rowObj;
            }
         }
      }

      return count;
   }

   private Integer dealExplainResultForHuaweiCloud(List result) {
      Integer count = 0;
      if (result.size() < 1) {
         return count;
      } else {
         HashMap firstHashMap = (HashMap)result.get(0);
         Object val = firstHashMap.values().toArray()[0];
         if (val != null) {
            String valStr = val.toString();
            int startIndex = valStr.indexOf("rows");
            int endIndex = valStr.indexOf("width");
            if (startIndex == -1 || endIndex == -1) {
               return count;
            }

            String rowsVal = valStr.substring(startIndex + 5, endIndex);
            if (StringUtils.isNotBlank(rowsVal)) {
               rowsVal = rowsVal.trim();
               count = Integer.parseInt(rowsVal);
            }
         }

         return count;
      }
   }

   private boolean hasAttributeParam(BodyCondition condition) {
      return StringUtils.isNotBlank(condition.getUpperColor()) || StringUtils.isNotBlank(condition.getLowerColor()) || condition.getGender() != null || condition.getUpperType() != null || condition.getUpperPattern() != null || condition.getLowerType() != null || condition.getLowerPattern() != null || condition.getBagType() != null || condition.getHat() != null || condition.getMoveDirection() != null || condition.getMoveSpeed() != null || StringUtils.isNotBlank(condition.getHeadMarkerStr()) || StringUtils.isNotBlank(condition.getBagTypeStr()) || StringUtils.isNotBlank(condition.getBodyAppendageStr()) || condition.getShoesColor() != null || StringUtils.isNotBlank(condition.getAgeSegmentStr()) || condition.getNation() != null || condition.getShoesStyle() != null;
   }

   private List getBodyOriginListByIds(List recordList) {
      List bodyOriginalList = Lists.newCopyOnWriteArrayList();
      Lists.partition(recordList, 100).parallelStream().forEach((ids) -> {
         bodyOriginalList.addAll(this.bodyOriginalMapper.queryByRecordIds(recordList));
      });
      this.sort(bodyOriginalList, (BodyCondition)null);
      List bodyOriginalVOList = new ArrayList();
      if (!bodyOriginalList.isEmpty()) {
         Iterator var4 = bodyOriginalList.iterator();

         while(var4.hasNext()) {
            BodyOriginal bodyOriginal = (BodyOriginal)var4.next();
            bodyOriginalVOList.add(this.wrapBodyOriginalVO(bodyOriginal));
         }
      }

      return bodyOriginalVOList;
   }

   private List<BodyVO> getBodyByIds(String recordIds) {
      Checks.checkNotEmpty(recordIds);
      List<String> recordList = Arrays.asList(recordIds.split(","));
      List<BodyVO> bodyVOList = new ArrayList();
      List<BodyFeature> bodyFeatureList = this.bodyFeatureMapper.queryByRecordIds(recordList);
      List<BodyOriginal> bodyOriginalList = this.bodyOriginalMapper.queryByRecordIds(recordList);
      if (bodyFeatureList.isEmpty() && bodyOriginalList.isEmpty()) {
         return bodyVOList;
      } else {
         List<Body> bodyList = this.wrapBodyList(bodyOriginalList, bodyFeatureList);
         bodyVOList = this.wrapBodyVOList(bodyList);
         return bodyVOList;
      }
   }

   private List<BodyVO> getBodyByParams(BodyDownloadCondition bodyCondition) {
      List<BodyVO> bodyVOList = new ArrayList<>();
      if (StringUtils.isNotBlank(bodyCondition.getDeviceId())) {
         bodyCondition.setDeviceId("('" + bodyCondition.getDeviceId().replace(",", "','") + "')");
      }

      List bodyFeatureList = this.bodyFeatureMapper.queryByConditionTest(bodyCondition);
      if (bodyFeatureList.isEmpty()) {
         return bodyVOList;
      } else {
         List recordIdList = new ArrayList();
         Iterator var6 = bodyFeatureList.iterator();

         while(var6.hasNext()) {
            BodyFeature bodyFeature = (BodyFeature)var6.next();
            recordIdList.add(bodyFeature.getRecordId());
         }

         List<BodyOriginal> bodyOriginalList = this.bodyOriginalMapper.queryByRecordIds(recordIdList);
         List<Body> bodyList = this.wrapBodyList(bodyOriginalList, bodyFeatureList);
         bodyVOList = this.wrapBodyVOList(bodyList);
         return bodyVOList;
      }
   }

   private void sort(List<BodyOriginal> bodyOriginalList, BodyCondition bodyCondition) {
      Collections.sort(bodyOriginalList, (o1, o2) -> {
         int order = o1.getAbsTime() > o2.getAbsTime() ? -1 : (Objects.equals(o1.getAbsTime(), o2.getAbsTime()) ? 0 : 1);
         if (bodyCondition != null && "asc".equalsIgnoreCase(bodyCondition.getOrder())) {
            order = -1 * order;
         }

         return order;
      });
   }

   private void sort(List<BodyOriginal> bodyOriginalList, boolean desc) {
      Collections.sort(bodyOriginalList, (o1, o2) -> {
         int order = o1.getAbsTime() > o2.getAbsTime() ? -1 : (Objects.equals(o1.getAbsTime(), o2.getAbsTime()) ? 0 : 1);
         if (!desc) {
            order = -1 * order;
         }

         return order;
      });
   }

   private boolean orderConvert(String order) {
      return order == null || !"asc".equalsIgnoreCase(order);
   }

   private DeviceObj getCameraInfo(String deviceId) {
      if (StringUtils.isBlank(deviceId)) {
         return null;
      } else {
         try {
            return (DeviceObj)this.deviceObjCache.get(deviceId, () -> {
               DeviceObj cameraInfo = null;

               try {
                  cameraInfo = this.devicesCache.get(deviceId);
                  if (cameraInfo != null && StringUtils.isNotBlank(cameraInfo.getName())) {
                     return cameraInfo;
                  }

                  ResponseData responseData = this.searchServiceFeign.coverInfo(deviceId);
                  if (responseData != null && responseData.getData() != null) {
                     return (DeviceObj)responseData.getData().get("device");
                  }
               } catch (Exception var4) {
                  log.error("{}", var4.getMessage());
               }

               return cameraInfo;
            });
         } catch (Exception var4) {
            DeviceObj cameraInfo = new DeviceObj();
            cameraInfo.setId(deviceId);
            cameraInfo.setName("未知");
            return cameraInfo;
         }
      }
   }

   private Page fullTextSearch(BodyCondition condition) {
      List recordList = new ArrayList();
      SearchParamEntry searchParamEntry = new SearchParamEntry();
      searchParamEntry.setText(condition.getSearchText());
      if (condition.getCurrentPage() != null && condition.getCurrentPage() >= 1 && condition.getPageSize() != null && condition.getPageSize() > 0) {
         int from = (condition.getCurrentPage() - 1) * condition.getPageSize();
         int size = condition.getPageSize();
         searchParamEntry.setResultRange(new SearchParamEntry.ResultRange(from, size));
      } else {
         searchParamEntry.setResultRange(new SearchParamEntry.ResultRange());
      }

      searchParamEntry.setTimeRange(new SearchParamEntry.TimeRange(condition.getStartTime(), condition.getEndTime()));
      SearchParamEntry.DeviceIdRange deviceIdRange = new SearchParamEntry.DeviceIdRange();
      if (StringUtils.isNotBlank(condition.getDeviceId())) {
         deviceIdRange.addDeviceIds(condition.getDeviceId());
         searchParamEntry.setDeviceIdRange(deviceIdRange);
      }

      SearchDataRequest dataRequest = new SearchDataRequest(IndexTypes.BODY_INDEX_TYPE, searchParamEntry);
      SearchDataResponse dataResponse = this.dataSearchClient.searchData(dataRequest);
      if (dataResponse.isSuccessful()) {
         Iterator var7 = dataResponse.getSources().iterator();

         while(var7.hasNext()) {
            SearchDataEntry dataEntry = (SearchDataEntry)var7.next();
            recordList.add(dataEntry.getRecordId());
         }
      } else {
         log.warn("searchData by searchText ={} execute failed", condition.getSearchText());
      }

      List data = new ArrayList();
      if (recordList.size() != 0) {
         data = this.getBodyOriginListByIds(recordList);
      }

      condition.updatePageInfo((List)data, Long.valueOf(dataResponse.getTotalHit()).intValue());
      return condition;
   }

   private List<BodyOriginal> fetchBodyOriginalByIds(List<String> recordList) {
      return (List)Lists.partition(recordList, 200).parallelStream().map((ids) -> {
         List<BodyOriginal> originals = this.cacheHelper.getOriginal(ids);
         List<BodyFeature> features = this.cacheHelper.getFeature(ids);
         Map featureMap = Maps.newHashMap();
         if (features != null) {
            features.forEach((feature) -> {
               BodyFeature var10000 = (BodyFeature)featureMap.put(feature.getRecordId(), feature);
            });
         }

         originals.forEach((original) -> {
            BodyFeature f = (BodyFeature)featureMap.get(original.getRecordId());
            if (f != null) {
               original.setLocation(f.getLocation());
            }

         });
         featureMap.clear();
         features.clear();
         return originals;
      }).reduce((bodyOriginals, bodyOriginals2) -> {
         List originals = Lists.newArrayList();
         originals.addAll(bodyOriginals);
         originals.addAll(bodyOriginals2);
         return originals;
      }).orElse(Lists.newArrayList());
   }

   private List<BodyOriginal> fetchBodyOriginal(List<Body> bodyList) {
      return Lists.partition(bodyList, 200).stream().map((bodys) -> {
         List<BodyOriginal> originals = Lists.newArrayList();
         List<String> ids = Lists.transform(bodys, (body) -> {
            return body.getRecordId();
         });
         List<BodyFeature> features = this.cacheHelper.getFeature(ids);
         Map<String, BodyFeature> featureMap = Maps.newHashMap();
         if (!CollectionUtils.isEmpty(features)) {
            features.forEach((feature) -> {
               BodyFeature var10000 = (BodyFeature)featureMap.put(feature.getRecordId(), feature);
            });
         }

         bodys.forEach((original) -> {
            BodyFeature f = (BodyFeature)featureMap.get(original.getRecordId());
            if (f != null) {
               original.setLocation(f.getLocation());
            }

            BodyOriginal bodyOriginal = new BodyOriginal();
            BeanUtils.copyProperties(original, bodyOriginal);
            originals.add(bodyOriginal);
         });
         featureMap.clear();
         features.clear();
         return originals;
      }).reduce((bodyOriginals, bodyOriginals2) -> {
         List<BodyOriginal> originals = Lists.newArrayList();
         originals.addAll(bodyOriginals);
         originals.addAll(bodyOriginals2);
         return originals;
      }).orElse(Lists.newArrayList());
   }

   private List<BodyOriginal> fetchBodyOriginalForFeature(List<Body> bodyList) {
      return Lists.partition(bodyList, 200).parallelStream().map((bodys) -> {
         List originals = Lists.newArrayList();
         List ids = Lists.transform(bodys, (body) -> {
            return body.getRecordId();
         });
         List<BodyOriginal> originals1 = this.cacheHelper.getOriginal(ids);
         Map originalMap = Maps.newHashMap();
         originals1.forEach((originalV2) -> {
            BodyOriginal var10000 = (BodyOriginal)originalMap.put(originalV2.getRecordId(), originalV2);
         });
         bodys.forEach((f) -> {
            BodyOriginal o = (BodyOriginal)originalMap.get(f.getRecordId());
            if (o != null) {
               o.setLocation(f.getLocation());
               originals.add(o);
            }
         });
         originalMap.clear();
         return originals;
      }).reduce((bodyOriginals, bodyOriginals2) -> {
         List originals = Lists.newArrayList();
         originals.addAll(bodyOriginals);
         originals.addAll(bodyOriginals2);
         return originals;
      }).orElse(Lists.newArrayList());
   }

   private int generateValue(String[] str) {
      int fRes = 0;
      if (null != str && str.length > 0) {
         String[] var3 = str;
         int var4 = str.length;

         for(int var5 = 0; var5 < var4; ++var5) {
            String s = var3[var5];
            if (!s.equals("0")) {
               int m = Integer.valueOf(s) - 1;
               fRes |= 1 << m;
            }
         }
      }

      return fRes;
   }

   private int generateValue(String s) {
      int fRes = 0;
      if (!s.equals("0")) {
         int m = Integer.valueOf(s) - 1;
         fRes |= 1 << m;
      }

      return fRes;
   }

   private String generateCode(int value) {
      String str = "";

      for(int i = 1; i <= 31; ++i) {
         int m = 1 << i - 1;
         if ((m & value) == m) {
            str = str + i + ",";
         }
      }

      return str.substring(0, str.length() - 1);
   }

   private void setAssociateValue(BodyCondition condition, RequestIdService.RequestAssociateValue associateValue) {
      if (StringUtils.isBlank(condition.getRequestId())) {
         this.requestIdService.set(associateValue);
         condition.setRequestId(associateValue.getRequestId());
      } else if (this.requestIdService.get(condition.getRequestId()) != null) {
         this.requestIdService.set(condition.getRequestId(), associateValue);
         associateValue.setRequestId(condition.getRequestId());
      } else {
         this.requestIdService.set(associateValue);
         condition.setRequestId(associateValue.getRequestId());
      }

   }

   private List fetchBodyOriginalForYouhua(List bodyList, BodyCondition condition) {
      List bodyOriginalList = new ArrayList();
      if (null != bodyList && bodyList.size() != 0) {
         if (condition.isQueryFeature()) {
            bodyOriginalList = this.fetchBodyOriginal(bodyList);
         } else {
            Iterator var4 = bodyList.iterator();

            while(var4.hasNext()) {
               Body body = (Body)var4.next();
               BodyOriginal bodyOriginal = new BodyOriginal();
               bodyOriginal.setRecordId(body.getRecordId());
               bodyOriginal.setDeviceId(body.getDeviceId());
               bodyOriginal.setSceneImg(body.getSceneImg());
               bodyOriginal.setTraitImg(body.getTraitImg());
               bodyOriginal.setAbsTime(body.getAbsTime());
               bodyOriginal.setSource(body.getSource());
               ((List)bodyOriginalList).add(bodyOriginal);
            }
         }

         return (List)bodyOriginalList;
      } else {
         return (List)bodyOriginalList;
      }
   }
}
